package com.scalar.chiptrack.commons.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.AttachedFile;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.dao.AttachFileDAO;
import com.scalar.chiptrack.commons.forms.AttachFileForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.FileUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * User: Sujan
 */
public class AttachFileAction extends ChipTrackAction {

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(SessionKeys.USER_KEY);
        if (user == null) {
            request.setAttribute("sessionExpired", "true");
            return mapping.findForward("attachFileForm");
        }
        HashMap errors = new HashMap();
        HashMap info = new HashMap();
        // Create and add Errors HashMap to the request
        request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);

        // Create and add Info Messages HashMap to the request
        request.setAttribute(SessionKeys.INFO_MESSAGES, info);

        AttachFileForm attachFileForm = (AttachFileForm) form;
        String action = request.getParameter("action");
        if ("saveAttachedFile".equalsIgnoreCase(action)) {
           /* if (isTokenValid(request)) {*/
                FormFile attachedFormFile = attachFileForm.getAttachedFormFile();
                if (attachedFormFile == null || attachedFormFile.getFileName() == null || attachedFormFile.getFileName().length() == 0) {
                    errors.put("Please select a file to attach", null);
                } else {
                    String fileName = attachedFormFile.getFileName();
                    String physicalFileName = FileUtils.getFileNameWithoutExtension(fileName);
                    physicalFileName += "_" + System.currentTimeMillis();
                    physicalFileName += "." + FileUtils.getFileExtension(fileName);

                    String directoryPath = ConfigManager.getProcessDocFilePath() + File.separator + attachFileForm.getFileGroup();
                    if (attachFileForm.getFileSubGroup() != null && attachFileForm.getFileSubGroup().trim().length() != 0) {
                        directoryPath += File.separator + attachFileForm.getFileSubGroup();
                    }
                    try {
                        String filePath = FileUtils.saveFile(physicalFileName, directoryPath, attachedFormFile.getInputStream());
                        System.out.println("Attachment saved to:" + filePath);
                        AttachedFile attachedFile = new AttachedFile();
                        attachedFile.setFileName(fileName);
                        attachedFile.setPhysicalFileName(physicalFileName);
                        attachedFile.setComments(attachFileForm.getComments());
                        attachedFile.setFileGroup(attachFileForm.getFileGroup());
                        attachedFile.setFileSubGroup(attachFileForm.getFileSubGroup());
                        attachedFile.setAttachedByUserId(user.getUserId());
                        AttachFileDAO.saveAttachedFile(null, attachedFile);
                        info.put("File attached successfully", null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        errors.put("Could not save attachment file", e.getMessage());
                    }
                }
            /*} else {
                errors.put("Invalid Request", "Attach file again");
            }*/
        } else if ("deleteAttachedFile".equalsIgnoreCase(action)) {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                AttachFileDAO.deleteAttachedFile(null, id);
                info.put("Attached File deleted successfully", null);
            } catch (Exception e) {
                e.printStackTrace();
                errors.put("Could not delete attached file", e.getMessage());
            }
        }
        /*saveToken(request);*/
        ArrayList attachedFileList = AttachFileDAO.getAttachedFileList(null, attachFileForm, false);
        request.setAttribute("attachedFileList", attachedFileList);

        return mapping.findForward("attachFileForm");
    }
}
